package user_api

import (
	"gin-vue/global"
	"gin-vue/modles/res"
	"gin-vue/modles/user"
	"github.com/gin-gonic/gin"
	"strconv"
)

func (UsersApi) UserCount(c *gin.Context) {
	var user []user.User
	rows := global.DB.Find(&user).RowsAffected
	res.OkWithData(rows, c)
}

// UserLogin 用户登录
func (UsersApi) UserLogin(c *gin.Context) {
	var user user.User
	no := c.PostForm("no")
	pwd := c.PostForm("password")
	global.DB.Take(&user, "no=?", no)
	if user.Password != pwd {
		res.FailWithMsg("用户名或密码错误", c)
		return
	}
	res.Ok(user, "登录成功", c)
}

// UserPage 用户分页
func (UsersApi) UserPage(c *gin.Context) {
	//分页查询通用写法
	var users []user.User
	// 一页多少条
	limit, _ := strconv.Atoi(c.Query("pageSize"))
	//fmt.Println("一页：", limit)
	// 第几页
	page, _ := strconv.Atoi(c.Query("pageNum"))
	name := c.Query("name")
	if limit == 0 || page == 0 {
		res.FailWithMsg("查询有误", c)
		return
	}
	offset := (page - 1) * limit //从第几条数据（offset+1）开始
	if name == "" {
		global.DB.Limit(limit).Offset(offset).Find(&users)
	}
	//fmt.Println("第：", page)
	global.DB.Limit(limit).Offset(offset).Find(&users)
	res.OkWithData(users, c)
}

func (UsersApi) UserSave(c *gin.Context) {
	var user user.User
	id := c.PostForm("id")

	name := c.PostForm("name")
	no := c.PostForm("no")
	age := c.PostForm("age")
	email := c.PostForm("email")
	if id == "" {
		user.Name = name
		user.Age, _ = strconv.Atoi(age)
		user.No = no
		user.Email = email
		global.DB.Create(&user)
		res.OkWithData(user, c)
		return
	}
	global.DB.Take(&user, id)
	user.Name = name
	user.Age, _ = strconv.Atoi(age)
	user.No = no
	user.Email = email
	global.DB.Save(&user)
	res.OkWithData(user, c)
}
